using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlan;
using ERP_SaaS_WinForm.生产计划_派单_车间.apiResquest;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_SaaS_WinForm.生产计划_派单_车间
{
    public partial class AddProductPlanForm : Form
    {
        private HttpClient httpClient;

        [DllImport("gdi32.dll")]
        private static extern IntPtr CreateRoundRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, int nWidthEllipse, int nHeightEllipse);

        public AddProductPlanForm()
        {
            InitializeComponent();
            httpClient = new HttpClient();
            
            // 检查JWT授权状态
            if (!JwtAuthHelper.EnsureLoggedIn())
            {
                MessageBox.Show("需要登录才能使用此功能", "授权提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.Close();
                return;
            }
            
            InitializeModernDesign();
            InitializeControls();
        }

        private void InitializeModernDesign()
        {
            this.BackColor = Color.FromArgb(245, 248, 250);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.Text = "新增生产计划";
            this.Size = new Size(800, 600);
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
        }

        private void InitializeControls()
        {
            // 创建主面板
            Panel mainPanel = new Panel
            {
                Dock = DockStyle.Fill,
                Padding = new Padding(20)
            };

            // 创建标题
            Label lblTitle = new Label
            {
                Text = "新增生产计划",
                Font = new Font("微软雅黑", 16, FontStyle.Bold),
                ForeColor = Color.FromArgb(64, 64, 64),
                Location = new Point(20, 20),
                Size = new Size(200, 30)
            };

            // 创建表单面板
            Panel formPanel = new Panel
            {
                Location = new Point(20, 60),
                Size = new Size(740, 420),
                BackColor = Color.White
            };

            // 创建输入控件
            int yOffset = 20;
            int labelX = 20;
            int textX = 120;
            int width = 200;

            // 计划编号
            Label lblPlanCode = new Label { Text = "计划编号:", Location = new Point(labelX, yOffset), Size = new Size(80, 25) };
            TextBox txtPlanCode = new TextBox { Location = new Point(textX, yOffset), Size = new Size(width, 25), Name = "txtPlanCode" };
            yOffset += 35;

            // 计划名称
            Label lblPlanName = new Label { Text = "计划名称:", Location = new Point(labelX, yOffset), Size = new Size(80, 25) };
            TextBox txtPlanName = new TextBox { Location = new Point(textX, yOffset), Size = new Size(width, 25), Name = "txtPlanName" };
            yOffset += 35;

            // 来源类型
            Label lblResource = new Label { Text = "来源类型:", Location = new Point(labelX, yOffset), Size = new Size(80, 25) };
            ComboBox cboResource = new ComboBox 
            { 
                Location = new Point(textX, yOffset), 
                Size = new Size(width, 25), 
                Name = "cboResource",
                DropDownStyle = ComboBoxStyle.DropDownList
            };
            yOffset += 35;

            // 产品名称
            Label lblProductName = new Label { Text = "产品名称:", Location = new Point(labelX, yOffset), Size = new Size(80, 25) };
            TextBox txtProductName = new TextBox { Location = new Point(textX, yOffset), Size = new Size(width, 25), Name = "txtProductName" };
            yOffset += 35;

            // 产品编号
            Label lblProductCode = new Label { Text = "产品编号:", Location = new Point(labelX, yOffset), Size = new Size(80, 25) };
            TextBox txtProductCode = new TextBox { Location = new Point(textX, yOffset), Size = new Size(width, 25), Name = "txtProductCode" };
            yOffset += 35;

            // 规格型号
            Label lblSpecification = new Label { Text = "规格型号:", Location = new Point(labelX, yOffset), Size = new Size(80, 25) };
            TextBox txtSpecification = new TextBox { Location = new Point(textX, yOffset), Size = new Size(width, 25), Name = "txtSpecification" };
            yOffset += 35;

            // 单位
            Label lblUnit = new Label { Text = "单位:", Location = new Point(labelX, yOffset), Size = new Size(80, 25) };
            TextBox txtUnit = new TextBox { Location = new Point(textX, yOffset), Size = new Size(width, 25), Name = "txtUnit" };
            yOffset += 35;

            // 计划数量
            Label lblPlanNum = new Label { Text = "计划数量:", Location = new Point(labelX, yOffset), Size = new Size(80, 25) };
            TextBox txtPlanNum = new TextBox { Location = new Point(textX, yOffset), Size = new Size(width, 25), Name = "txtPlanNum" };
            yOffset += 35;

            // 开工时间
            Label lblPlanStart = new Label { Text = "开工时间:", Location = new Point(labelX, yOffset), Size = new Size(80, 25) };
            DateTimePicker dtpPlanStart = new DateTimePicker 
            { 
                Location = new Point(textX, yOffset), 
                Size = new Size(width, 25), 
                Name = "dtpPlanStart",
                Format = DateTimePickerFormat.Short
            };
            yOffset += 35;

            // 完工时间
            Label lblPlanEnd = new Label { Text = "完工时间:", Location = new Point(labelX, yOffset), Size = new Size(80, 25) };
            DateTimePicker dtpPlanEnd = new DateTimePicker 
            { 
                Location = new Point(textX, yOffset), 
                Size = new Size(width, 25), 
                Name = "dtpPlanEnd",
                Format = DateTimePickerFormat.Short
            };
            yOffset += 35;

            // 需求日期
            Label lblRequireDate = new Label { Text = "需求日期:", Location = new Point(labelX, yOffset), Size = new Size(80, 25) };
            DateTimePicker dtpRequireDate = new DateTimePicker 
            { 
                Location = new Point(textX, yOffset), 
                Size = new Size(width, 25), 
                Name = "dtpRequireDate",
                Format = DateTimePickerFormat.Short
            };

            // 右侧列
            int rightLabelX = 400;
            int rightTextX = 500;
            int rightYOffset = 20;

            // 销售订单ID
            Label lblSalesOrderId = new Label { Text = "销售订单ID:", Location = new Point(rightLabelX, rightYOffset), Size = new Size(80, 25) };
            TextBox txtSalesOrderId = new TextBox { Location = new Point(rightTextX, rightYOffset), Size = new Size(width - 30, 25), Name = "txtSalesOrderId", ReadOnly = true };
            Button btnSelectSale = new Button 
            { 
                Text = "选择", 
                Location = new Point(rightTextX + width - 25, rightYOffset), 
                Size = new Size(50, 25), 
                Name = "btnSelectSale",
                BackColor = Color.FromArgb(0, 122, 204),
                ForeColor = Color.White
            };
            rightYOffset += 35;

            // 产品ID
            Label lblProductId = new Label { Text = "产品ID:", Location = new Point(rightLabelX, rightYOffset), Size = new Size(80, 25) };
            TextBox txtProductId = new TextBox { Location = new Point(rightTextX, rightYOffset), Size = new Size(width - 30, 25), Name = "txtProductId", ReadOnly = true };
            Button btnSelectProduct = new Button 
            { 
                Text = "选择", 
                Location = new Point(rightTextX + width - 25, rightYOffset), 
                Size = new Size(50, 25), 
                Name = "btnSelectProduct",
                BackColor = Color.FromArgb(0, 122, 204),
                ForeColor = Color.White
            };
            rightYOffset += 35;

            // 添加控件到表单面板
            formPanel.Controls.AddRange(new Control[] {
                lblPlanCode, txtPlanCode, lblPlanName, txtPlanName, lblResource, cboResource,
                lblProductName, txtProductName, lblProductCode, txtProductCode, lblSpecification, txtSpecification,
                lblUnit, txtUnit, lblPlanNum, txtPlanNum, lblPlanStart, dtpPlanStart,
                lblPlanEnd, dtpPlanEnd, lblRequireDate, dtpRequireDate,
                lblSalesOrderId, txtSalesOrderId, btnSelectSale, lblProductId, txtProductId, btnSelectProduct
            });

            // 创建按钮面板
            Panel buttonPanel = new Panel
            {
                Location = new Point(20, 500),
                Size = new Size(740, 50),
                BackColor = Color.Transparent
            };

            // 创建按钮
            Button btnSubmit = new Button
            {
                Text = "提交",
                Location = new Point(300, 10),
                Size = new Size(100, 35),
                BackColor = Color.FromArgb(0, 122, 204),
                ForeColor = Color.White,
                Font = new Font("微软雅黑", 10),
                Name = "btnSubmit"
            };

            Button btnCancel = new Button
            {
                Text = "取消",
                Location = new Point(420, 10),
                Size = new Size(100, 35),
                BackColor = Color.FromArgb(128, 128, 128),
                ForeColor = Color.White,
                Font = new Font("微软雅黑", 10),
                Name = "btnCancel"
            };

            buttonPanel.Controls.AddRange(new Control[] { btnSubmit, btnCancel });

            // 添加所有面板到主面板
            mainPanel.Controls.AddRange(new Control[] { lblTitle, formPanel, buttonPanel });

            // 添加主面板到窗体
            this.Controls.Add(mainPanel);

            // 初始化来源类型下拉框
            var resourceList = new List<OrderSource>
            {
                new OrderSource { Value = 0, Name = "请选择来源类型" },
                new OrderSource { Value = 1, Name = "销售订单" },
                new OrderSource { Value = 2, Name = "库存备货" },
                new OrderSource { Value = 3, Name = "其他" }
            };
            cboResource.DataSource = resourceList;
            cboResource.DisplayMember = "Name";
            cboResource.ValueMember = "Value";
            cboResource.SelectedIndex = 0;

            // 设置默认值
            dtpPlanStart.Value = DateTime.Now;
            dtpPlanEnd.Value = DateTime.Now.AddDays(7);
            dtpRequireDate.Value = DateTime.Now.AddDays(7);

            // 绑定事件
            btnSubmit.Click += BtnSubmit_Click;
            btnCancel.Click += BtnCancel_Click;
            btnSelectSale.Click += BtnSelectSale_Click;
            btnSelectProduct.Click += BtnSelectProduct_Click;
        }

        private async void BtnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidateInput())
                {
                    // 禁用提交按钮，防止重复点击
                    Button btnSubmit = (Button)sender;
                    btnSubmit.Enabled = false;
                    btnSubmit.Text = "提交中...";

                    var planData = new PlanData
                    {
                        planCode = GetControlValue<TextBox>("txtPlanCode"),
                        planName = GetControlValue<TextBox>("txtPlanName"),
                        resource = GetComboBoxValue<ComboBox>("cboResource"),
                        productName = GetControlValue<TextBox>("txtProductName"),
                        productCode = GetControlValue<TextBox>("txtProductCode"),
                        specification = GetControlValue<TextBox>("txtSpecification"),
                        unitName = GetControlValue<TextBox>("txtUnit"),
                        planNum = int.Parse(GetControlValue<TextBox>("txtPlanNum")),
                        planStart = GetDateTimePickerValue<DateTimePicker>("dtpPlanStart"),
                        planEnd = GetDateTimePickerValue<DateTimePicker>("dtpPlanEnd"),
                        requireDate = GetDateTimePickerValue<DateTimePicker>("dtpRequireDate"),
                        planState = 0, // 默认未分解
                        createName = ERP_SaaS_WinForm.登录.Common.TokenDto.Name ?? "系统用户", // 从登录token获取创建人
                        createDate = DateTime.Now,
                        productId = int.TryParse(GetControlValue<TextBox>("txtProductId"), out int productId) ? productId : 0,
                        state = 0, // 默认状态
                        salesOrderId = int.TryParse(GetControlValue<TextBox>("txtSalesOrderId"), out int salesOrderId) ? salesOrderId : 0
                    };

                    var apiResponse = await ApiRequestHelper.PostAsync<AddPlanApiResponse>("api/Plan/AddPlan", planData);

                    if (apiResponse.Success)
                    {
                        if (apiResponse.Data.code == 200)
                        {
                            ApiRequestHelper.ShowSuccess("生产计划新增成功！");
                            this.DialogResult = DialogResult.OK;
                            this.Close();
                        }
                        else
                        {
                            ApiRequestHelper.ShowError($"新增失败: {apiResponse.Data.msg}");
                        }
                    }
                    else
                    {
                        ApiRequestHelper.ShowError($"请求失败: {apiResponse.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"新增生产计划失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复按钮状态
                Button btnSubmit = (Button)sender;
                btnSubmit.Enabled = true;
                btnSubmit.Text = "提交";
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private bool ValidateInput()
        {
            if (string.IsNullOrWhiteSpace(GetControlValue<TextBox>("txtPlanCode")))
            {
                MessageBox.Show("请输入计划编号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                GetControl<TextBox>("txtPlanCode").Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(GetControlValue<TextBox>("txtPlanName")))
            {
                MessageBox.Show("请输入计划名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                GetControl<TextBox>("txtPlanName").Focus();
                return false;
            }

            if (GetComboBoxValue<ComboBox>("cboResource") == 0)
            {
                MessageBox.Show("请选择来源类型", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                GetControl<ComboBox>("cboResource").Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(GetControlValue<TextBox>("txtProductName")))
            {
                MessageBox.Show("请输入产品名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                GetControl<TextBox>("txtProductName").Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(GetControlValue<TextBox>("txtPlanNum")) || !int.TryParse(GetControlValue<TextBox>("txtPlanNum"), out int num) || num <= 0)
            {
                MessageBox.Show("请输入有效的计划数量", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                GetControl<TextBox>("txtPlanNum").Focus();
                return false;
            }

            return true;
        }

        private T GetControl<T>(string controlName) where T : Control
        {
            return this.Controls.Find(controlName, true).FirstOrDefault() as T;
        }

        private string GetControlValue<T>(string controlName) where T : Control
        {
            var control = GetControl<T>(controlName);
            if (control is TextBox textBox)
                return textBox.Text.Trim();
            return "";
        }

        private int GetComboBoxValue<T>(string controlName) where T : Control
        {
            var control = GetControl<T>(controlName);
            if (control is ComboBox comboBox && comboBox.SelectedValue != null)
                return (int)comboBox.SelectedValue;
            return 0;
        }

        private DateTime? GetDateTimePickerValue<T>(string controlName) where T : Control
        {
            var control = GetControl<T>(controlName);
            if (control is DateTimePicker dateTimePicker)
                return dateTimePicker.Value;
            return null;
        }

        /// <summary>
        /// 选择销售订单按钮点击事件
        /// </summary>
        private void BtnSelectSale_Click(object sender, EventArgs e)
        {
            try
            {
                var selectSaleForm = new SelectSale();
                if (selectSaleForm.ShowDialog() == DialogResult.OK && selectSaleForm.SelectedSale != null)
                {
                    var selectedSale = selectSaleForm.SelectedSale;
                    
                    // 回显销售单ID
                    GetControl<TextBox>("txtSalesOrderId").Text = selectedSale.SalesOrderId.ToString();
                    
                    // 回显销售数量到计划数量
                    GetControl<TextBox>("txtPlanNum").Text = selectedSale.SaleNumder.ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择销售订单失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 选择产品按钮点击事件
        /// </summary>
        private void BtnSelectProduct_Click(object sender, EventArgs e)
        {
            try
            {
                var selectProductForm = new SelectProduct();
                if (selectProductForm.ShowDialog() == DialogResult.OK && selectProductForm.SelectedProduct != null)
                {
                    var selectedProduct = selectProductForm.SelectedProduct;
                    GetControl<TextBox>("txtProductId").Text = selectedProduct.ProductId.ToString();
                    
                    // 同时填充相关的产品信息
                    GetControl<TextBox>("txtProductName").Text = selectedProduct.ProductName ?? "";
                    GetControl<TextBox>("txtProductCode").Text = selectedProduct.ProductCode ?? "";
                    GetControl<TextBox>("txtSpecification").Text = selectedProduct.Specification ?? "";
                    GetControl<TextBox>("txtUnit").Text = selectedProduct.UnitName ?? "";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择产品失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


    }
} 